<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Services\Log;
use Exception;
use Closure;

class ApiSignVerify
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        try
        {
            $input  = $request->all();

            if (! isset($input['sign'])) {
                throw new ApiException('参数不正确',0);
            }
            if (! isset($input['ClientSource'])) {
                throw new ApiException('参数不正确',0);
            }
            if (isset($input['s'])) {
                unset($input['s']);
            }
            $client_sign = $input['sign'];
            if (substr($client_sign,0,3) == 'TY-') {
                if ($client_sign == config('basic.TY_sign')){
                    return $response;
                }
            }
            unset($input['sign']);
            ksort($input);
            $str = '';
            foreach($input  as $k=>$v){
                $str .= ($k . '=' . $v . "&");
            }
            $str = substr($str , 0 , -1);
            $sign = md5($str);
            if(strtolower($client_sign) != strtolower($sign)){
                throw new ApiException('签名验证失败',0);
            }
        } catch (Exception $e) {
            $response->header('Access-Control-Allow-Origin', '*');
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', false);
            if ($e instanceof ApiException)
            {
                throw $e;
            }
            else
            {
                throw new ApiException($e->getMessage(),0,$e);  
            }
        }

        return $response;
    }

    /**
     * 未参数提供签名字段
     *
     * @param [type] $request
     * @return void
     * @date 
     * @version v1.0
     */
/*     static function AddSign($request)
    {
        $str = '';
        foreach($request  as $k=>$v){
            $str .= ($k . '=' . $v . "&");
        }
        $str = substr($str , 0 , -1);
        $sign = md5($str);
        $request['sign'] = $sign;
        return $request;
    } */
}
